package com.htx.zqs.blesmartmask.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.util.Log;

import com.google.gson.Gson;
import com.htx.zqs.blesmartmask.MyApplication;
import com.htx.zqs.blesmartmask.bean.AfterCourseData;
import com.htx.zqs.blesmartmask.bean.BeforeCourseData;
import com.htx.zqs.blesmartmask.bean.Contants;
import com.htx.zqs.blesmartmask.listeners.OkListener;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.entity.StringEntity;
import timber.log.Timber;

/**
 * Created by KomoriWu
 * 上传课程、油水数据
 * on 2019/3/6.
 */
public class UpNetWaterData {
    private Activity activity;
    private List<BeforeCourseData> beforeCourseList;
    private List<AfterCourseData> afterCourseList;

    public UpNetWaterData(Activity activity) {
        this.activity = activity;
    }

    public static UpNetWaterData create(Activity activity) {
        return new UpNetWaterData(activity);
    }

    public void cacheUp() {
        startUp(false);
        Timber.e("上传缓存数据");
    }

    /**
     * 一整个课程做完了，上传课程、油水数据 isSingle=true为上传单条数据
     */
    public void startUp(boolean isSingle) {
        //上传之前的油水值
        beforeCourseList = BeforeCourseData.findAllNoUp();

        //上传之后的油水值
        afterCourseList = AfterCourseData.findAllNoUp();


        if (beforeCourseList.size() > 0) {
            if (isSingle) {
                upBeforeSingle(beforeCourseList.get(0));
            } else {
                for (BeforeCourseData beforeCourseData : beforeCourseList) {
                    beforeCourseData.setName(Utils.getCourseName(beforeCourseData.getCoursedate()));
                }
                String jsonBefore = new Gson().toJson(beforeCourseList);
                upBefore(jsonBefore);
            }

            //防止一个课程只上传一次
            for (AfterCourseData afterCourseData : afterCourseList) {
                //上传用户信息、电压
                upUserInfo(afterCourseData);
            }
        }

        if (beforeCourseList.size() == 0 && afterCourseList.size() > 0) {
            if (isSingle) {
                upAfterSingle(afterCourseList.get(0));
            } else {
                for (AfterCourseData afterCourseData : afterCourseList) {
                    afterCourseData.setName(Utils.getCourseName(afterCourseData.getCoursedate()));
                }
                String jsonAfter = new Gson().toJson(afterCourseList);
                upAfter(jsonAfter);
            }
        }


    }

    private void upUserInfo(AfterCourseData afterCourseData) {
        OkhttpUtils okhttpUtils = new OkhttpUtils(activity, 0x0002, new OkListener() {
            @Override
            public void onSuccess(int requestCode, String string) {

            }

            @Override
            public void onError(int requestCode, IOException e) {
            }
        });
        HashMap<String, String> map = new HashMap<>();
        map.put("voltage", afterCourseData.getVoltage());
        map.put("nickname", MySpUtils.getString(MySpUtils.KEY_USER_NAME));
        map.put("device", LocationUtil.getUniquePsuedoID());
        map.put("course", afterCourseData.getName());
        map.put("time", afterCourseData.getTime());
        map.put("voltagedate", afterCourseData.getAfterdate());
        map.put("address", Utils.getCurMac());
        okhttpUtils.postForm(0x0002, Contants.URL_USER_VOLTAGE, map);
    }

    private void upBeforeSingle(BeforeCourseData beforeCourseData) {
        OkhttpUtils okhttpUtils = new OkhttpUtils(activity, 0x0001, new OkListener() {
            @Override
            public void onSuccess(int requestCode, String string) {
                Timber.e("上传课程之前的油水值单条onSuccess");
                //上传成功标记数据为已上传状态
                BeforeCourseData.updateUpState();

                if (afterCourseList.size() > 0) {
                    upAfterSingle(afterCourseList.get(afterCourseList.size() - 1));
                }
            }

            @Override
            public void onError(int requestCode, IOException e) {
            }
        });
        HashMap<String, String> map = new HashMap<>();
        map.put("name", Utils.getCourseName(beforeCourseData.getCoursedate()));
        map.put("coursedate", beforeCourseData.getCoursedate());
        map.put("deviceid", LocationUtil.getUniquePsuedoID());
        map.put("beforeffat", String.valueOf(beforeCourseData.getBeforeffat()));
        map.put("beforefwater", String.valueOf(beforeCourseData.getBeforefwater()));
        map.put("beforedate", beforeCourseData.getBeforedate());
        map.put("islogo", "A");
        map.put("address", Utils.getCurMac());
        Timber.e("上传课程之前的油水值单条:" + beforeCourseData.toString());
        okhttpUtils.postForm(0x0001, Contants.URL_INSERT_BEFATTWO, map);
    }

    private void upAfterSingle(final AfterCourseData afterCourseData) {
        Timber.e("上传课程之后的油水值单条:" + afterCourseData.toString());
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("name", Utils.getCourseName(afterCourseData.getCoursedate()));
        params.put("coursedate", afterCourseData.getCoursedate());
        params.put("deviceid", LocationUtil.getUniquePsuedoID());
        params.put("afterdate", afterCourseData.getAfterdate());
        params.put("afterfwater", String.valueOf(afterCourseData.getAfterfwater()));
        params.put("afterffat", String.valueOf(afterCourseData.getAfterffat()));
        params.put("islogo", "A");
        params.put("address", Utils.getCurMac());
        client.post(Contants.URL_INSERT_AFFATTWO, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                Log.e("rs", response.toString());
                Timber.e("上传课程之后的油水值单条onSuccess");
                //上传成功标记数据为已上传状态
                AfterCourseData.updateUpState();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
            }
        });
    }

    @SuppressLint("CheckResult")
    private void upBefore(String jsonBefore) {
        Timber.e("上传课程之前的油水值:" + jsonBefore);
        OkhttpUtils okhttpUtils = new OkhttpUtils(activity, Contants.BEFORE_WATER_LIST, new OkListener() {
            @Override
            public void onSuccess(int requestCode, String string) {
                Timber.e("上传课程之前的油水值onSuccess");
                //上传成功标记数据为已上传状态
                BeforeCourseData.updateUpState();

                if (afterCourseList.size() > 0) {
                    for (AfterCourseData afterCourseData : afterCourseList) {
                        afterCourseData.setName(Utils.getCourseName(afterCourseData.getCoursedate()));
                    }
                    String jsonAfter = new Gson().toJson(afterCourseList);
                    upAfter(jsonAfter);
                }
            }

            @Override
            public void onError(int requestCode, IOException e) {
            }
        });
        okhttpUtils.postJson(Contants.BEFORE_WATER_LIST, Contants.URL_BEFORE_WATER_LIST, jsonBefore);


    }

    private void upAfter(String jsonAfter) {
        Timber.e("上传课程之后的油水值:" + jsonAfter);
        AsyncHttpClient client = new AsyncHttpClient();
        StringEntity requestEntity = new StringEntity(jsonAfter, "utf-8");
        client.post(activity, Contants.URL_AFTER_WATER_LIST, requestEntity, "application/json", new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                Log.e("rs", response.toString());
                Timber.e("上传课程之后的油水值onSuccess");
                //上传成功标记数据为已上传状态
                AfterCourseData.updateUpState();

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
            }
        });

    }
}
